﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace Kokomo.IO
{
	public class BlockStreamBuilder : BlockStream
	{
		public BlockStreamBuilder()
		{
			this.Blocks = new Queue<byte[]>();
			this.BlockAddEvent = new ManualResetEvent(false);
		}

		public ManualResetEvent BlockAddEvent { get; private set; }

		protected override void Dispose(bool disposing)
		{
			base.Dispose(disposing);
			this.BlockAddEvent.Dispose();
		}

		protected void AddBlock(byte[] data)
		{
			ArgumentValidation.CheckNullArgument("data", data);
			this.BlockAddEvent.Set();
			lock (this.Blocks)
			{
				this.Blocks.Enqueue(data);
			}
		}
		public Queue<byte[]> Blocks { get; private set; }
		protected override byte[] GetNextBlock()
		{
			byte[] block;
			this.BlockAddEvent.WaitOne();
			lock (this.Blocks)
			{
				if (this.Blocks.Count == 0)
				{
					return null;
				}
				block = this.Blocks.Dequeue();
				if (this.Blocks.Count == 0 && !this.EosMarked)
				{
					this.BlockAddEvent.Reset();
				}
			}
			return block;
		}

		public bool EosMarked { get; private set; }
		protected void MarkEos()
		{
			this.EosMarked = true;
			this.BlockAddEvent.Set();
		}
	}
}
